package main.carteleracm.ca.utils;


import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import main.carteleracm.ca.data.Pelicula;
import main.carteleracm.ca.db.PeliculaDB;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {

	private Timer timer = new Timer();
	private static final long UPDATE_INTERVAL_MINUTOS = 360;//6h
		
	private static MyService instance  = null;
	
	public static boolean isInstanceCreated() { 
	      return instance != null; 
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		//Toast.makeText(getApplicationContext(), "Servicio creado CarteleraCM", Toast.LENGTH_LONG).show();
		System.out.println( "Servicio creado CarteleraCM");
		instance=this;
	}

	@Override
	public void onDestroy() {
		//Toast.makeText(getApplicationContext(), "Servicio destruido CarteleraCM", Toast.LENGTH_LONG).show();
		System.out.println( "Servicio destruido CarteleraCM");
		instance = null;
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		//Toast.makeText(getApplicationContext(), "Servicio iniciado CarteleraCM", Toast.LENGTH_LONG).show();
		System.out.println( "Servicio iniciado CarteleraCM");
		descargarInformacionDiariamente();

	}
	
	private void descargarInformacionDiariamente(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY,cal.get(Calendar.HOUR_OF_DAY)+6);
		cal.set(Calendar.MINUTE,0);
		cal.set(Calendar.SECOND,0);
		timer.scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					System.out.println( "actualizando informacion CarteleraCM");
					List<Pelicula> pel=null;
					Data data = new Data();
					SP sp = new SP(getApplicationContext());
					PeliculaDB peldb = new PeliculaDB(getApplicationContext(), PeliculaDB.NOMBRE_DB, null, 1);
					try{
						pel=data.getPeliculas(sp.getString(sp.PAIS),sp.getString(sp.SALA));
						peldb.insertPeliculas(pel,sp.getString(sp.PAIS),sp.getString(sp.SALA));
					}catch(Exception e){
						e.printStackTrace();
						System.out.println( "ERROR!! actualizando informacion CarteleraCM");
					}
				}
			},cal.getTime(), 60000*UPDATE_INTERVAL_MINUTOS);//ejecutarse por primera dentro de 6h a partir de la hora actual y repitiendose cada 6h
	}	
}